package cn.loioi.web.components.shiro;

import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import cn.loioi.multi.service.user.LoginService;

/**
 * 用户身份识别/权限校验
 * @文件 :CustomAuthorizingRealm.java
 * @作者 :cn.loioi
 * @创建时间 :2016年10月13日 下午12:56:59
 */
public class CustomAuthorizingRealm extends AuthorizingRealm implements ApplicationContextAware {
	private Logger logger = LoggerFactory.getLogger(CustomAuthorizingRealm.class);
	private LoginService loginService;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		loginService = applicationContext.getBean(LoginService.class);
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		logger.debug("执行授权信息...");
		try {
			String username = (String) getAvailablePrincipal(principals);
			// 获取用户角色/权限列表
			List<String> roles = loginService.roles(username);
			List<String> resources = loginService.permission(username);

			SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
			authorizationInfo.addRoles(roles);
			authorizationInfo.addStringPermissions(resources);
			return authorizationInfo;
		} catch (Exception e) {
			logger.error(e.getMessage());
			throw new UnauthenticatedException();
		}
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		logger.debug("执行身份验证信息...");
		try {
			// 获取用户信息
			String user = loginService.login(String.valueOf(token.getPrincipal()));
			return new SimpleAuthenticationInfo(token.getPrincipal(), user, getName());
		} catch (Exception e) {
			logger.error(e.getMessage());
			throw new AuthenticationException();
		}
	}

}
